<template>
  <el-card class="app-container">
    <div>
      <div class="itemTitle">页面标题</div>
      <div class="search">
    <el-form :inline="true" :model="queryParams" ref="queryForm">
<el-col :span="5">
      <el-form-item label="学生名称" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生名称"
          clearable
        />
      </el-form-item>
</el-col>
      <el-col :span="5">
      <el-form-item>
        <el-button type="primary"  @click="handleQuery">搜索</el-button>
        <el-button  @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-col>
    </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['test:students:add']">页面新增</el-button>
          <el-button type="primary" @click="handleAddByDialog" v-hasPermi="['test:students:add']">弹窗新增</el-button>
          <el-button type="success" @click="handleImport" v-hasPermi="['test:students:import']">批量导入</el-button>
          <el-button type="warning"  @click="handleExport" v-hasPermi="['test:students:export']">批量导出</el-button>
          <el-button type="warning"  @click="importTemplate" v-hasPermi="['test:students:downImportTemplate']">下载导入模板</el-button>
        </div>
        <div class="ct-table">
          <elTables
              :table-data="tableData"
              :columns="tableColumns"
              :totalLength="total"
              :handle-current-change="handleCurrentChange"
              isPagin
              :curHeight="tableHeight"
          />
        </div>
      </div>
      </div>
    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open"  append-to-body @close="cancel" class="dialog-form">
      <p class="title-level2">二级标题可选</p>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
<el-col :span="12">
        <el-form-item label="学生名称" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生名称" :readonly="!isEdit" :disabled="!isEdit"/>
        </el-form-item>
</el-col>
<el-col :span="12">
        <el-form-item label="年龄" prop="studentAge">
          <el-input v-model="form.studentAge" placeholder="请输入年龄" :readonly="!isEdit" :disabled="!isEdit"/>
        </el-form-item>
</el-col>
<el-col :span="12">
        <el-form-item label="爱好" prop="studentHobby">
          <el-input v-model="form.studentHobby" placeholder="请输入爱好" :readonly="!isEdit" :disabled="!isEdit"/>
        </el-form-item>
</el-col>
<el-col :span="12">
        <el-form-item label="性别" prop="studentSex">
          <el-select v-model="form.studentSex" placeholder="请选择性别" :readonly="!isEdit" :disabled="!isEdit">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
</el-col>
<el-col :span="12">
        <el-form-item label="状态">
          <el-radio-group v-model="form.studentStatus" :readonly="!isEdit" :disabled="!isEdit">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
</el-col>
<el-col :span="12">
        <el-form-item label="生日" prop="studentBirthday">
          <el-date-picker clearable size="small" :readonly="!isEdit" :disabled="!isEdit"
            v-model="form.studentBirthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择生日">
          </el-date-picker>
        </el-form-item>
</el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
        :title="upload.title"
        :visible.sync="upload.open"
        width="800px"
        append-to-body
    >
      <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
  const defaultQueryParams = {
    pageNum: 1,
    pageSize: 10,
  };
  import { getToken } from "@/utils/auth";
import { pageStudents,listStudents, getStudents, delStudents, addStudents, updateStudents, exportStudents ,downImportTemplate} from "@/api/test/students";
      
export default {
  name: "Students",
  data() {
    return {
      tableHeight:0,
      isEdit:false,
      dialogFormVisible:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
            process.env.VUE_APP_BASE_API + "/specialWork/contractor/importData",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,

        studentName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentName: [
          { required: true, message: "学生名称不能为空", trigger: "blur" }
        ],
        studentAge: [
          { required: true, message: "年龄不能为空", trigger: "blur" }
        ],
        studentHobby: [
          { required: true, message: "爱好不能为空", trigger: "blur" }
        ],
        studentSex: [
          { required: true, message: "性别不能为空", trigger: "change" }
        ],
        studentStatus: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
      },
      tableColumns: [
          { key:"studentName",title:"学生名称"},
      { key:"studentAge",title:"年龄"},
      { key:"studentHobby",title:"爱好（0代码 1音乐 2电影）"},
      { key:"studentSex",title:"性别（0男 1女 2未知）"},
      { key:"studentStatus",title:"状态（0正常 1停用）"},
      { key:"studentBirthday",title:"生日"},
        {
          title: "操作",
          align: "center",
          fixed:'right',
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["test:students:edit"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleUpdate(params.row,1);
                      },
                    },
                  },
                  "编辑"
              ),
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["test:students:info"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleUpdate(params.row,2)
                      },
                    },
                  },
                  "查看"
              ),
              h(
                  "el-button",
                  {
                    props: {
                      type: "text",
                      size: "small",
                    },
                    directives: [
                      {
                        name: "hasPermi",
                        value: ["test:students:remove"],
                      },
                    ],
                    on: {
                      click: () => {
                        this.handleDelete(params.row)
                      },
                    },
                  },
                  "删除"
              ),
            ]);
          },
        },
      ]

    };
  },
  created() {
    this.getPage();
  },
  mounted(){
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    /** 下载模板操作 */
    importTemplate() {
      downImportTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    handleAddByDialog(){
      this.dialogFormVisible=true;
    },
    getTableHeight(){
      let height=document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight= height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询学生信息列表 */
    getPage() {
      this.loading = true;
      pageStudents(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        studentName: null,
        studentAge: null,
        studentHobby: null,
        studentSex: null,
        studentStatus: "0",
        studentBirthday: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit= true;
      this.title = "新增学生信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row,type) {
        if(type==1){
          this.isEdit=true;
        }else{
          this.isEdit=false;
        }
      this.reset();
      const studentId = row.studentId || this.ids
      getStudents(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑学生信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateStudents(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addStudents(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
            let data
            if(Array.isArray(studentIds)){
              data=studentIds
            }else{
              data=[studentIds]
            }
          return delStudents(data);
        }).then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有学生信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStudents(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
<style lang="scss" scoped>

</style>
